<!-- 商品列表 -->
<template>
  <div class="goodsList sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="商品名称:">
              <el-input v-model="query.name" placeholder="请输入商品名称" clearable/>
            </el-form-item>
            <el-form-item label="商品编号:">
              <el-input v-model="query.productCode" placeholder="请输入商品编号" clearable/>
            </el-form-item>
            <el-form-item label="上架状态:">
              <el-select v-model="query.enableStatus" placeholder="请选择" clearable>
                <el-option label="上架" value="1" />
                <el-option label="下架" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态:">
              <el-select v-model="query.verifyStatus" placeholder="请选择" clearable>
                <el-option label="审核中" :value="0" />
                <el-option label="通过" :value="1" />
                <el-option label="驳回" :value="2" />
                <el-option label="创建中" :value="3" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="商品列表数据" icon="Goods" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table :data="dataList" max-height="493" border>
          <el-table-column label="编号" type="index" align="center" width="60"></el-table-column>
          <el-table-column label="商品图片" prop="pic" align="center" width="100">
            <template #default="{row}">
              <div class="img-cell">
                <el-image :src="row.pic + '?x-oss-process=image/resize,m_fill,h_40,w_40'"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
          <el-table-column label="编号" prop="productCode" align="center"></el-table-column>
          <el-table-column label="厂商" prop="merchantName" align="center"></el-table-column>
          <el-table-column label="价格(元)" prop="salePrice" align="center"></el-table-column>
          <el-table-column label="SKU信息" align="center" width="100">
            <template #default="{row}">
              <el-button type="primary" icon="EditPen" circle @click="toViewSku(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="上架状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已上架' : '未上架' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" prop="verifyStatus" align="center">
            <template #default="{row}">
              <el-tag v-if="row.verifyStatus === 0">审核中</el-tag>
              <el-tag v-if="row.verifyStatus === 1" type="success">通过</el-tag>
              <el-tag v-if="row.verifyStatus === 2" type="danger">驳回</el-tag>
              <el-tag v-if="row.verifyStatus === 3" type="info">创建中</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template #default="{row}">
              <el-button v-if="row.verifyStatus === 2 || row.verifyStatus === 3" type="primary" icon="Stamp" link @click="doExamine(row.productId)">提交审核</el-button>
              <el-divider v-if="row.verifyStatus === 3" direction="vertical" />
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.productId)">修改</el-button>
              <el-divider v-if="row.verifyStatus === 1" direction="vertical" />
              <el-button 
                v-if="row.verifyStatus === 1"
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'"
                link 
                @click="doPublish(row)">
                {{ row.enableStatus ? '下架' : '上架' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 商品的添加/编辑弹窗 -->
    <el-drawer 
      v-model="show" 
      :with-header="false" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true" 
      size="89.6%">
      <new-goods @close="doChose"></new-goods>
    </el-drawer>

    <!-- 查看SKU -->
    <el-dialog v-model="skuShow" :title="title" top="10vh" width="60%" draggable>
      <el-table :data="skuList" :header-cell-style="{fontSize:'12px'}" max-height="400" border size="small">
        <el-table-column v-for="item in skuTableHeader" :key="item.prop" :label="item.label" :prop="item.prop" :fixed="item.prop.indexOf('specs') !== -1" align="center">
          <template #default="{row}">
            <div v-if="item.prop === 'skuPic'" class="sku-pic-box">
              <upload-img v-model="row.skuPic" width="40" height="40" iconSize="20" style="margin-top: -10px;"></upload-img>
            </div>
            <span v-else-if="/^\d+$/.test(item.prop)">{{ row[item.prop] }}</span>
            <el-input v-else v-model="row[item.prop]" type="number" placeholder="请输入" size="small"/>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button type="primary" size="default" @click="doUpdateSku">保存</el-button>
        <el-button size="default" @click="skuShow = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="goodsList">
  import newGoods from './comps/index.vue'
  import { getGoodsListPagesApi, updateGoodsVerifyStatusApi, updateGoodsPublishStatusApi, getGoodsSkuInfoApi, updateGoodsSkuApi } from '@/api/api'
  import { reactive, toRefs, getCurrentInstance, onActivated } from 'vue'
  import { useStore } from 'vuex' 

  const store = useStore()
  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties

  const currentData = reactive({
    loading: false,
    show: false,
    skuShow: false,
    query: {
      name: '',
      productCode: '',
      enableStatus: '',
      verifyStatus: '',
      productType: '0',
      current: 1,
      size: 20,
      total: 0
    },
    dataList: [],
    title: '',
    skuTableHeader: [],
    skuList: []
  })
  let {
    loading, 
    show,
    skuShow,
    query, 
    dataList, 
    title, 
    skuTableHeader, 
    skuList
  } = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getGoodsListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 修改弹窗
  function toUpdate(productId) {
    store.commit('productId', productId)
    currentData.show = true
  }

  // 提交审核
  function doExamine(productId) {
    currentThis.$messageBox.confirm('确认提交审核吗？').then(() => {
      const loading = currentThis.$loading('提交中，请耐心等待')
      updateGoodsVerifyStatusApi({ productId: productId, verifyStatus: 0 }).then(res => {
        loading.close()
        if(res.code === '200') {
          load(currentData.query.current)
          currentThis.$message.success('提交审核成功')
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 上架或下架
  function doPublish(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '下架' : '上架'}吗？`).then(() => {
      const loading = currentThis.$loading('正在处理，请耐心等待')
      updateGoodsPublishStatusApi(e.productId, e.enableStatus ? 0 : 1).then(res => {
        loading.close()
        if(res.code === '200') {
          load(currentData.query.current)
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 查看sku信息
  function toViewSku(e) {
    currentData.title = `商品编号：${e.productCode}`
    getGoodsSkuInfoApi(e.productId).then(res => {
      if(res.code === '200') {
        let tableHeader = [
          {label: 'SKU图标', prop: 'skuPic'},
          {label: '出厂价', prop: 'oriPrice'},
          {label: '销售价', prop: 'salePrice'},
          {label: '库存', prop: 'stocks'},
          {label: '库存预警值', prop: 'lowStock'},
          {label: '赠送积分', prop: 'giftPoint'},
          {label: '金积分', prop: 'agentPoint'}
        ]
        res.data.headList.forEach((item, index) => {
          tableHeader.splice(index, 0, {label: item.name, prop: item.attributeId})
        })
        currentData.skuTableHeader = tableHeader
        currentData.skuList = res.data.infoList
        currentData.skuShow = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 修改商品sku
  function doUpdateSku() {
    currentThis.$messageBox.confirm(`确认修改吗？`).then(() => {
      let loading = currentThis.$loading('修改中，请耐心等待')
      updateGoodsSkuApi(currentData.skuList).then(res => {
        loading.close()
        if(res.code === '200') {
          currentData.skuShow = false
          load(currentData.query.current)
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 关闭新增，编辑商品弹窗
  function doChose() {
    load(currentData.query.current)
    currentData.show = false
  }

  // 重置查询
  function resetSearch() {
    currentData.query.name = ''
    currentData.query.productCode = ''
    currentData.query.enableStatus = ''
    currentData.query.verifyStatus = ''
    load(1)
  }

  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.goodsList{
  .img-cell{
    display: flex;
    justify-content: center;
    align-items: center;
    .el-image{
      width: 40px; 
      height: 40px;
      border-radius: 5px;
    }
  }
  :deep(.el-dialog){
    .sku-pic-box{
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  :deep(.el-drawer){
    .el-drawer__body{
      padding: 0 !important;
    }
  }
}
</style>